#!/usr/bin/env python
#­*­ coding:utf8 ­*­ 

# adn
   


from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
if 'nt' in sys.builtin_module_names:
    sys.path.append("./pythonmodules")
import mh
import os
import subprocess
import webbrowser
from script import *

sys.path.append("./")
sys.path.append("./mh_plugins")
sys.path.append("./mh_core")

import gui3d, events3d
import human, hair
import guimodelling, guifiles, guirender

class MHApplication(gui3d.Application):
  def getHuman(self):
    return self.scene3d.selectedHuman
  def __init__(self):
    gui3d.Application.__init__(self)
    
    self.setTheme("default")
    
    # Display the initial splash screen and the progress bar during startup 
    self.splash = gui3d.Object(self, "data/3dobjs/splash.obj", self.getThemeResource("images", "splash.png"), position = [0, 0, 0])
    self.progressBar = gui3d.ProgressBar(self, backgroundTexture = self.getThemeResource("images", "progressbar_background.png"),
      barTexture = self.getThemeResource("images", "progressbar.png"))
    self.scene3d.update()
    self.scene3d.redraw(0)
 
    
   
    gui3d.Object(self, "data/3dobjs/backgroundbox.obj", position = [0, 0, -72])

    
    #self.progressBar.setProgress(0.3)
    
    #self.scene3d.selectedHuman = humanbis.Human(self.scene3d, "data/3dobjs/base.obj")
    self.scene3d.selectedHuman = human.Human(self.scene3d, "data/3dobjs/base.obj")
	##self.scene3d.selectedHuman.setMuscle()
    self.scene3d.selectedHuman.setTexture("data/textures/texture.tif")
    
    #self.progressBar.setProgress(0.6)
    
    self.tool = None
    self.selectedGroup = None
    
    self.undoStack = []
    self.redoStack = []
    


## AFFICHAGE ET EVENEMENTS DES BOUTONS DE L'INTERFACE

## FAIRE MOOVER LE PERSONNAGE DANS LE LAYER

  
    @self.scene3d.selectedHuman.event
    def onMouseDown(event):
      if self.tool:
        self.selectedGroup = self.app.scene3d.getSelectedFacesGroup()
        self.tool.callEvent("onMouseDown", event)
      else:
        self.currentTask.callEvent("onMouseDown", event)
      
    @self.scene3d.selectedHuman.event
    def onMouseMoved(event):
      if self.tool:
        self.tool.callEvent("onMouseMoved", event)
      else:
        self.currentTask.callEvent("onMouseMoved", event)
      
    @self.scene3d.selectedHuman.event
    def onMouseDragged(event):
      if self.tool:
        self.tool.callEvent("onMouseDragged", event)
      else:
        self.currentTask.callEvent("onMouseDragged", event)
      
    @self.scene3d.selectedHuman.event
    def onMouseUp(event):
      if self.tool:
        self.tool.callEvent("onMouseUp", event)
      else:
        self.currentTask.callEvent("onMouseUp", event)
        
    @self.scene3d.selectedHuman.event
    def onMouseEntered(event):
      if self.tool:
        self.tool.callEvent("onMouseEntered", event)
      else:
        self.currentTask.callEvent("onMouseEntered", event)
      
    @self.scene3d.selectedHuman.event
    def onMouseExited(event):
      if self.tool:
        self.tool.callEvent("onMouseExited", event)
      else:
        self.currentTask.callEvent("onMouseExited", event)
      
    # Set up categories and tasks  
  


    # Exit button
    category = gui3d.Category(self, "Exit", self.getThemeResource("images", "button_exit.png"))
    @category.button.event

    def onClicked(event):
      self.stop()
    
    guimodelling.ModellingCategory(self)
    #self.progressBar.setProgress(0.7)
    guifiles.FilesCategory(self)
    #self.progressBar.setProgress(0.8)
    guirender.RenderingCategory(self)
    
    #library = gui3d.Category(self, "Library", self.getThemeResource("images", "button_library.png"))
    #hair.HairTaskView(library)
    
    category = gui3d.Category(self, "Help", self.getThemeResource("images", "button_about.png"))


    # Help button
    @category.button.event
    def onClicked(event):
      webbrowser.open(os.getcwd()+"/docs/MH_Users_Guide.pdf");
    
    self.switchCategory("Modelling")
    
    self.progressBar.setProgress(1.0)
    self.progressBar.hide()
    
  def onStart(self, event):
      self.splash.hide()
      self.scene3d.selectedHuman.applyAllTargets()
      mh.updatePickingBuffer();
    
  
  def setTheme(self, theme):
    f = open("data/themes/" + theme + ".mht", 'r')
      
    for data in f.readlines():
      lineData = data.split()
      
      if len(lineData) > 0:
        if lineData[0] == "version":
          print("Version " + lineData[1])
        elif lineData[0] == "color":
          if lineData[1] == "clear":
            mh.setClearColor(float(lineData[2]), float(lineData[3]), float(lineData[4]), float(lineData[5]))
    
    self.theme = theme
  
  def getThemeResource(self, folder, id):
    return "data/themes/" + self.theme + "/" + folder + "/"+ id

class Choix(QWidget):
    def __init__(self, application, parent=None):
        self.application = application 
        self.humain = application.getHuman()
        self.mainScene = application.scene3d


        QWidget.__init__(self, parent) #--> utilité ??
	        # Declaration Layout

        layout_principale = QVBoxLayout()            #Fenetre principale
        layout_menu = QHBoxLayout()                  #Liste menu bouton (ouvrir, sauvegarde, quitter)                  
        layout_affichage = QHBoxLayout()             #Layout principal d'affichage
        layout_gen = QVBoxLayout()                   #Layout de la liste des genes
        layout_allele_age = QHBoxLayout()            # Stock le label + le combo box
        layout_allele_genre = QHBoxLayout()              
        layout_allele_muscle = QHBoxLayout()             
        layout_allele_weight = QHBoxLayout()               
        layout_allele_ethni = QHBoxLayout()               

        #Declaration des boutons du menu
        self.ouvrir = QPushButton("Ouvrir")
        self.sauvegarder = QPushButton("Sauvegarder")
        self.quitter= QPushButton("Quitter")


        #Declaration des comboBox
        self.combo_age = QComboBox()
        self.combo_genre = QComboBox()
        self.combo_muscle = QComboBox()
        self.combo_weight = QComboBox()
        self.combo_ethni = QComboBox()

        #Bouton de modélisation
        self.modelisation = QPushButton("Modeliser")
        self.test = QPushButton("Test")

        # Déclaration Label des Genes
        self.Label_age = QLabel("Age")
        self.Label_genre = QLabel("Sexe")
        self.Label_muscle = QLabel("Corpulence")
        self.Label_weight = QLabel("Poids")
        self.Label_ethni = QLabel("Ethni")

        #Insertion dans les combo box
        self.combo_age.addItem("Jeune", QVariant(1))        
        #self.combo_age.setAccessibleDescription("0")
        self.combo_genre.addItem("Femme")
        self.combo_genre.addItem("Homme")
        self.combo_genre.insertItem(2, "enfant")        


        #ajout des bouton primaire dans le layout_menu
        layout_menu.addWidget(self.ouvrir)
        layout_menu.addWidget(self.sauvegarder)
        layout_menu.addWidget(self.quitter)    

        #Ajouts des gene + allene 
        layout_allele_age.addWidget(self.Label_age)
        layout_allele_age.addWidget(self.combo_age)
        layout_allele_genre.addWidget(self.Label_genre)
        layout_allele_genre.addWidget(self.combo_genre)
        layout_allele_muscle.addWidget(self.Label_muscle)
        layout_allele_muscle.addWidget(self.combo_muscle)
        layout_allele_weight.addWidget(self.Label_weight)
        layout_allele_weight.addWidget(self.combo_weight)
        layout_allele_ethni.addWidget(self.Label_ethni)
        layout_allele_ethni.addWidget(self.combo_ethni)

        #Ajout des genes dans son layout principal
        layout_gen.addLayout(layout_allele_age)
        layout_gen.addLayout(layout_allele_genre)
        layout_gen.addLayout(layout_allele_muscle)
        layout_gen.addLayout(layout_allele_weight)
        layout_gen.addLayout(layout_allele_ethni)
        layout_gen.addWidget(self.modelisation)
        layout_gen.addWidget(self.test)

        #layout affichage + gene 
        layout_affichage.addLayout(layout_gen)
        #layout_affichage.addWidget(QWidget(application))

        #Ajout des 2 grandes partie dans le layout principale
        layout_principale.addLayout(layout_menu)
        layout_principale.addLayout(layout_affichage)

        
        self.setLayout(layout_principale)

        self.quitter.connect(self.quitter,SIGNAL("clicked(bool)"),self.fermer)
        self.modelisation.connect(self.modelisation,SIGNAL("clicked(bool)"),self.modeliser)
        self.test.connect(self.test,SIGNAL("clicked(bool)"),self.tester)

    def tester(self):
        print self.combo_age.itemData(2).toInt()

    def fermer(self):    # genere l'evenement closeEvent 
        self.close()   

    def modeliser(self):
        #self.close()
        self.application = MHApplication()
        self.mainScene = self.application.scene3d # HACK: Don't remove this, it is needed to receive events from C
        self.application.start()
        

    '''     
        self.buttonBox.addWidget(self.button)
        layout.addLayout(self.buttonBox, 3, 1)  #cette ligne peut être modifié
        self.setLayout(layout)

        self.connect(self.button,SIGNAL("clicked(bool)"),self.accept)
        self.connect(self.button,SIGNAL("rejected()"),self.fermer)        
	
    def choix_bis(self, humain):
         humain.setAge(0.2)
         humain.setGender(0.4)
         humain.setMuscle(0.5)
	 humain.setWeight(0.2)

    def getHumain(self):
    	return self.humain


    def accept(self):
        self.humain.setAge(float(self.age.text()))
        self.humain.setGender(float(self.genre.text()))
        self.humain.setMuscle(float(self.muscle.text()))
        self.humain.setWeight(float(self.weight.text()))
        ecran = QDesktopWidget().screenGeometry() #resolution de l'ecran
        tailleWidget =  self.geometry() #dimension du widget
        self.move((ecran.width()-tailleWidget.width())/2, (ecran.height()-tailleWidget.height())/2)
        self.close()

  


    def closeEvent(self, event):     #traitement de l'evenement closeEvent
        reponse = QMessageBox.question(self, 'Message',
            "Voulez vous confirmer cette/ces saisie(s)?", QMessageBox.Yes, QMessageBox.No)
        if reponse == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

   '''

